import { Component, OnInit } from '@angular/core';
import { NzMessageService, UploadFile } from 'ng-zorro-antd';
import { ApiService } from 'src/app/core/api';
import { MessageService } from 'src/app/core/service/message.service';
import { FormBuilder, Validators } from '@angular/forms';
import { urlService } from './../../../core/api/url';
import { Router, ActivatedRoute } from '@angular/router';
import { DatePipe } from '@angular/common';
import { I18nService } from 'src/app/core/i18n/i18n.service';

@Component({
	templateUrl: './travelAgencyAdd.html',
	providers: [DatePipe],
})
export class TravelAgencyAddComponent implements OnInit {
	areaList = [];
	agencyServiceItemList = [];
	classifyList = [];
	validateForm;
	fileList = [];
	previewImage;
	showTime = false;
	uploadUrl = urlService('dev', '上传图(唯一路口)');
	personalityTagObj: any = {};
	agencyServiceItemObj: any = {};
	noSelect = false;
	language = {
		userLevel:{},
		starLevel:{}
	};
	id;
	constructor(private i18n:I18nService,private apiService: ApiService, private nzMessageService: NzMessageService, private message: MessageService, private fb: FormBuilder, private router: Router, private datePipe: DatePipe, private activeRouter: ActivatedRoute) {
		this.id = this.activeRouter.snapshot.queryParams['id'];
		this.i18n.get(["userLevel","starLevel"]).subscribe(res=>{
			this.language = res;
		})
	}

	ngOnInit() {
		this.validateForm = this.fb.group({
			name: [null, [Validators.required]],
			areaId: [null, [Validators.required]],
			address: [null, [Validators.required]],
			starLevel: [null, [Validators.required]],
			contactName: [null, [Validators.required]],
			contactTel: [null, [Validators.required, Validators.pattern(/^[\d\-]+$/)]],
			reservationFee: [null, [Validators.required, Validators.pattern(/((^[1-9]\d*)|^0)(\.\d{0,3}){0,1}$/)]],
			allowMemberLevel: [null, [Validators.required]],
			time: [[{ weekday: 'monOpenTime', timeStart: new Date('1990-01-01 09:00'), timeEnd: new Date('1990-01-01 18:00') }], [Validators.required]],
			agencyServiceItemList: [null],
			brief: [null, [Validators.required]],
			cateIds:[null,[]]
		});
		if (this.id) {
			this.apiService.post('旅行社详情', { id: this.id }).then((res: any) => {
				const { name, areaNameId: areaId, address, starLevel, contactName, contactTel, reservationFee, brief, allowMemberLevel } = res.data.travelAgencyDetail;
				const cateList = [];
				if(res.data.agencyTravelCategoryList && res.data.agencyTravelCategoryList.length>0){
					res.data.agencyTravelCategoryList.forEach(e=>{
						cateList.push(e.cateId);
					})
				}
				res.data.travelAgencyDetail.serviceItemList.forEach(item => {
					this.agencyServiceItemObj[item.name] = item.id;
				});
				this.validateForm.patchValue({
					name,
					areaId,
					address,
					starLevel: String(starLevel),
					contactName,
					contactTel,
					reservationFee,
					brief,
					allowMemberLevel,
					time: this.getTimeList(res.data.travelAgencyDetail),
					agencyServiceItemList: Object.keys(this.agencyServiceItemObj),
					cateIds:cateList.length>0?cateList:null
				});
				this.fileList = res.data.travelAgencyDetail.images.split(',').map(item => {
					return { url: item, status: 'done', thumbUrl: item, uid: item };
				});
				console.log(res);
			});
		}
		this.message.setBreadcrumb({
			breadcrumbs: [{ name: '机构管理' }],
		});
		this.apiService.post('地区列表(用于选择框)', {}).then((res: any) => {
			this.areaList = res.data.list;
		});
		this.apiService.post('获取服务项目', {}).then((res: any) => {
			this.agencyServiceItemList = res.data;
		});
		this.apiService.post('旅游分类列表', {pageNo:1,mode:'DESIGNATED',providerType:'AGENCY'}).then((res: any) => {
			this.classifyList = res.data.list;
		});
	}
	handlePreview = (file: UploadFile) => {
		this.previewImage = file.url || file.thumbUrl;
		window.open(this.previewImage);
	};
	getTimeList(data) {
		const array = [];
		const timer = new Date().getTime();
		if (data.monOpenTime) {
			array.push({ weekday: 'monOpenTime', timeStart: new Date('1990-01-01 ' + data.monOpenTime), timeEnd: new Date('1990-01-01 ' + data.monCloseTime) });
		}
		if (data.tueOpenTime) {
			array.push({ weekday: 'tueOpenTime', timeStart: new Date('1990-01-01 ' + data.tueOpenTime), timeEnd: new Date('1990-01-01 ' + data.tueCloseTime) });
		}
		if (data.wedOpenTime) {
			array.push({ weekday: 'wedOpenTime', timeStart: new Date('1990-01-01 ' + data.wedOpenTime), timeEnd: new Date('1990-01-01 ' + data.wedCloseTime) });
		}
		if (data.thuOpenTime) {
			array.push({ weekday: 'thuOpenTime', timeStart: new Date('1990-01-01 ' + data.thuOpenTime), timeEnd: new Date('1990-01-01 ' + data.thuCloseTime) });
		}
		if (data.friOpenTime) {
			array.push({ weekday: 'friOpenTime', timeStart: new Date('1990-01-01 ' + data.friOpenTime), timeEnd: new Date('1990-01-01 ' + data.friCloseTime) });
		}
		if (data.satOpenTime) {
			array.push({ weekday: 'satOpenTime', timeStart: new Date('1990-01-01 ' + data.satOpenTime), timeEnd: new Date('1990-01-01 ' + data.satCloseTime) });
		}
		if (data.sunOpenTime) {
			array.push({ weekday: 'sunOpenTime', timeStart: new Date('1990-01-01 ' + data.sunOpenTime), timeEnd: new Date('1990-01-01 ' + data.sunCloseTime) });
		}
		if (array.length < 1) {
			array.push({ weekday: 'monOpenTime', timeStart: new Date('1990-01-01 09:00'), timeEnd: new Date('1990-01-01 18:00') });
		}
		return array;
	}
	change(item) {
		console.log(item);
		if (item.type === 'success') {
			if (item.file.response) {
				if (item.file.response.status === '0') {
					this.fileList[this.fileList.length - 1].url = item.file.response.data.url;
				} else {
					item.fileList.pop();
					this.nzMessageService.warning(item.file.response.message);
				}
			}
		} else if (item.type === 'error') {
			if (item.file.response) {
				if (item.file.response.status === 403) {
					this.router.navigateByUrl('/pages/login');
				} else {
					this.nzMessageService.warning(item.file.response.message);
				}
			} else {
				this.nzMessageService.warning('未知错误，请联系管理员');
			}
			item.fileList.pop();
		}
	}
	addTime(i) {
		this.showTime = true;
	}
	removeTime(i) {
		this.showTime = false;
		this.validateForm.patchValue({ timeStart2: null, timeEnd2: null, timeType2: null });
	}
	agencyServiceItemChange(e, item) {
		if (e) {
			this.agencyServiceItemObj[item.name] = item.id;
		} else {
			delete this.agencyServiceItemObj[item.name];
		}
		const array = Object.keys(this.agencyServiceItemObj);
		this.validateForm.controls.agencyServiceItemList.setValue(array);
	}
	changeAgencyService(model) {
		console.log(model);
		let add = '';
		const obj = {};
		model.forEach(element => {
			if (this.agencyServiceItemObj[element]) {
				obj[element] = this.agencyServiceItemObj[element];
			} else {
				obj[element] = 999;
				add = element;
			}
		});
		if (add) {
			this.apiService.post('创建服务项目', { name: add }).then((res: any) => {
				obj[add] = res.data.id;
				this.agencyServiceItemObj = obj;
			});
		} else {
			this.agencyServiceItemObj = obj;
		}
	}
	filterOption = () => {
		return null;
	};
	beforeUpload = (file) => {
		console.log(file);
		if (file.size > 1024 * 1024) {
			this.nzMessageService.warning('上传图片不能大于1MB');
			return false;
		} else {
			return true;
		}
	}
	submit() {
		console.log(this.validateForm.value);
		for (const v in this.validateForm.controls) {
			this.validateForm.controls[v].markAsDirty();
			this.validateForm.controls[v].updateValueAndValidity();
		}
		if (this.validateForm.valid) {
			if (this.showTime) {
				if (!this.validateForm.value.timeStart2 || !this.validateForm.value.timeEnd2 || !this.validateForm.value.timeType2) {
					this.nzMessageService.warning('请填写或删除多余的上班时间选项！');
					return;
				}
			}
			if (this.fileList.length < 2) {
				this.nzMessageService.warning('请上传至少两张图片！');
				return;
			}
			const { name, areaId, address, starLevel, contactName, contactTel, reservationFee, allowMemberLevel, brief, time,cateIds } = this.validateForm.value;

			const data: any = {
				name,
				areaId,
				address,
				starLevel,
				contactName,
				contactTel,
				reservationFee,
				brief,
				allowMemberLevel,
				cateIds:cateIds||[]
			};
			data.time = {};
			for (let i = 0; i < time.length; i++) {
				const element = time[i];
				if (!element.weekday || !element.timeStart || !element.timeEnd) {
					this.nzMessageService.warning('营业时间不允许留空！');
					return;
				}
				data.time[element.weekday] = this.datePipe.transform(element.timeStart, 'HH:mm') + '-' + this.datePipe.transform(element.timeEnd, 'HH:mm');
			}
			data.agencyServiceItemList = Object.values(this.agencyServiceItemObj);
			data.images = [];
			this.fileList.forEach(e => {
				data.images.push(e.url);
			});
			if (this.id) {
				data.id = Number(this.id);
			}
			console.log(this.id);
			const url = this.id ? '编辑旅行社' : '创建旅游社';
			this.apiService.post(url, data).then((res: any) => {
				this.nzMessageService.success(url + '成功！');
				this.router.navigateByUrl('/basicSetting/travelAgency');
			});
		}
	}
}
